package com.example.electricbicycle.dao;


import com.example.electricbicycle.po.VehicleStock;
import utils.DBUtils;
import java.sql.*;

public class VehicleStockDaoImpl implements VehicleStockDao {

    public boolean addStock(int vId, int quantity) {

        String sql = "INSERT INTO vehicle_stock (v_id, quantity) VALUES (?, ?)";
        try (Connection conn = DBUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, vId);
            pstmt.setInt(2, quantity);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }


    // 更新库存
    public boolean updateStock(int vId, int quantity) {
        String sql = "UPDATE vehicle_stock SET quantity = ?, last_update = CURRENT_TIMESTAMP WHERE v_id = ?";
        try (Connection conn = DBUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, quantity);
            pstmt.setInt(2, vId);
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取库存信息
    public VehicleStock getStockByVId(int vId) {
        String sql = "SELECT * FROM vehicle_stock WHERE v_id = ?";
        try (Connection conn = DBUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, vId);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return new VehicleStock(
                            rs.getInt("id"),
                            rs.getInt("v_id"),
                            rs.getInt("quantity"),
                            rs.getTimestamp("last_update")
                    );
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
    //删除库存信息
    public boolean deleteStock(int id) throws SQLException {
        String sql = "DELETE FROM vehicle_stock WHERE id = ?";
        try (Connection conn = DBUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, id);
            return pstmt.executeUpdate() > 0;
        }
    }






}